package handlers

import (
	"article-url/models"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	comment := c.PostForm("comment")

	if title == "" || content == "" || author == "" || comment == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := models.Article{
		Title:   title,
		Content: content,
		Author:  author,
		Comment: comment,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var article []models.Article
	models.DB.Offset(offset).Limit(size).Find(&article)
	c.JSON(200, gin.H{
		"code": 200,
		"data": article,
		"msg":  "ok",
	})
}
